﻿using System;
using System.Data;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using Progresoft.Scheduler.RemoteInterface.Api;
using Progresoft.Scheduler.RemoteInterface;
using System.Collections.Specialized;
using System.Collections.Generic;

/// <summary>
/// ConnectorManager
/// </summary>
public static class ConnectorManager
{
    private static string configSectionPath = "Progresoft.Scheduler/servers";
    
    /// <summary>
    /// Получить коннектор, зарегистрировав список систем
    /// </summary>
    /// <returns></returns>
	public static Connector GetConnector()
	{
		Connector toReturn = (Connector)HttpContext.Current.Application["connector"];
		if (toReturn == null)
		{
			toReturn = LoadConnectorFromConfig();
			HttpContext.Current.Application["connector"] = toReturn;
		}
		return toReturn;
	}

	private static Connector LoadConnectorFromConfig()
	{
		Connector connector = new Connector();
#warning 15.08.2008 Денис, для кого варнинги при компиляции пишутся?!
#warning 20080-08-18 И что ты хотел этим сказать, Вова?
        NameValueCollection settings = (NameValueCollection)ConfigurationSettings.GetConfig(configSectionPath);
        foreach (string key in settings.AllKeys)
        {
            connector.RegisterServer(key, settings.GetValues(key)[0]);
		}
		return connector;
	}

	/// <summary>
	/// Получить урл шедулера с кешированием результата
	/// </summary>
	/// <param name="system"></param>
	public static string GetServerUrl(string system)
	{
		string serverUrl = (string)HttpContext.Current.Cache["server_url_cached_" + system];
		if (string.IsNullOrEmpty(serverUrl))
		{
			serverUrl = ConnectorManager.GetConnector().GetServerUrlBySystem(system);
			HttpContext.Current.Cache.Add("server_url_cached_" + system, serverUrl, 
				null, DateTime.Now.AddMinutes(10), System.Web.Caching.Cache.NoSlidingExpiration, 
				System.Web.Caching.CacheItemPriority.Default, null);
		}
		return serverUrl;		
	}
}
